<template>
  <div>
    <h2 :class="{'active':isActive}">购物车案例</h2>
    <template v-if="list.length">
      <el-table border :data="list">
        <el-table-column label="序号" type="index" style="width:100px;"></el-table-column>
        <el-table-column label="商品名称" prop="name">
          <template slot-scope="scope">
            {{scope.row.name}}
            <el-button size="mini" class="yb-btn input-search">
              我是摆设不是按钮
              <i class="yb-icon icon-time"></i>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="商品单价" prop="price"></el-table-column>
        <el-table-column label="购买数量">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleReduce(scope.$index,scope.row)"
              type="text"
              :disabled="scope.row.count===0"
            >-</el-button>
            {{scope.row.count}}
            <el-button size="mini" type="text" @click="handleAdd(scope.$index)">+</el-button>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="small" type="success" @click="handleRemove(scope.$index)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <h3>总价：{{totalPrice}}</h3>
    </template>

    <h4 v-else>购物车为空！</h4>
  </div>
</template>


<script>
export default {
  name: 'buyCar',
  data () {
    return {
      isActive: true,
      list: [
        {
          id: 1,
          name: 'iphone7',
          price: 6188,
          count: 1
        },
        {
          id: 2,
          name: 'iphone9',
          price: 8900,
          count: 1
        },
        {
          id: 3,
          name: 'iphone7 Plus',
          price: 7599,
          count: 1
        }
      ]
    }
  },
  computed: {
    /* 这里需要对商品总结处理，所以在计算属性中处理 */
    totalPrice () {
      var total = 0
      for (let i = 0; i < this.list.length; i++) {
        var item = this.list[i]
        total += item.price * item.count //总价    
      }
      /* 返回总商品的总价 */
      return total.toString().replace(/(\d{4})(?=[^\s])/g, '$1,')
    }
  },

  methods: {
    /* 减少数据按钮 */
    handleReduce (index, row) {
      if (this.list.length === 1) return
      this.list[index].count--
    },
    /* 增加商品数量按钮 */
    handleAdd (index) {
      this.list[index].count++
    },
    /* 移除商品按钮 */
    handleRemove (index) {
      // console.log(index)
      this.list.splice(index, 1)
    }
  }
}
</script>

<style scoped>
.active {
  width: 1000px;
  height: 100px;
  text-align: center;
}
</style>
